import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus' //在js文件中，需单独引入提示
import md5 from 'md5'
import store from '@/store';

const server = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 50000
})
//实现code
function getTestICode() {
    const now = parseInt(Date.now() / 1000)
    const code = now + 'LGD_Sunday-1991'
    return {
        icode: md5(code),
        time: now
    }
}

//请求拦截
server.interceptors.request.use(config => {
    // 添加 icode 设置code
    const { icode, time } = getTestICode()
    config.headers.icode = icode
    config.headers.codeType = time

    config.headers.Authorization = `Bearer ${store.state.token}` //在请求头里保存token
    
    return config // 必须返回配置
}, error => {
    Promise.reject(error)
})

//响应拦截
server.interceptors.response.use(res => {
    console.log(res, "aaa");
    let code = res.data.code //响应状态码
    let msg = res.data.message;    //提示信息

    // 消息提示
    if (code == 200 || code == 201 || code == 1000) {
        if (msg != "") {
            ElMessage.success({
                duration: 1000,
                message: msg
            })
        } else {
            ElMessage.error(msg)
        }
    }

    if (msg == "无效token") {
        ElMessageBox.confirm('token过期, 是否跳转到登录页面?', '提示', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            //原生js方法跳转
            location.href = '/login'
        }).catch(() => {
        })
    }

    //对错误状态码进行精细控制
    if (code === 400 || code === 401 || code === 403 || code === 404 || code === 500) {
        ElMessage.error({
            duration: 1000,
            message: msg
        })
    }
    return res.data;

}, error => {
    //接口请求，响应错误-一般都是网络问题，进行处理
    console.log('响应错误', error);
    let { message } = error;
    if (message == "Network Error") {
        message = "后端接口连接异常";
    }
    else if (message.includes("timeout")) {
        message = "系统接口请求超时";
    }
    ElMessage({
        message: message,
        type: 'error',
        duration: 1000
    })

    Promise.reject(error)
})
export default server
